var focusedTreeItem;
var focusedTreeNode;
var focusedHierarchyItem;

function exceptionHandler(errorString, exception) {
	alert("Error: " + errorString + 
		"\nException:" + exception);
}

function initializeHierarchyDialog() {
	
	/*
	 * If the element is on page, create the dialog,
	 * register the event handler.
	 */
	if ($("#hierarchyTreeDialog")) {
		$("#hierarchyTreeDialog").dialog({
			autoOpen: false,
			height: 480,
			width: 640,
			modal: true,
			resizable: false,
			title: "Choose Hierarchy Item"
		});
		$("#hierarchyItemNameHandle").click(function(){
			$("#hierarchyTreeDialog").dialog("open");
			return false;
		});
		
		
	}
	
}

function initializeHierarchyTree() {
	initializeHierarchyDialog();
	var treeUrl = applicationBase + "hierarchy/view!json.action";
	$("#hierarchyTree").tree({
		types: {
			"default" : {
				clickable: true
			}	
		},
		data: {
			type: "json",
			async: true,
			opts: {
				async: true,
				url: treeUrl
			}
		},
		callback: {
    		beforedata: function(NODE, TREE_OBJ) {
      			return $(NODE).attr("id") === "" ?
       			{ id: $(NODE).find("a:first").attr("id")} :
       			{ id: $(NODE).attr("id") || 0 };
    		},
    		check_move: function(NODE, REF_NODE, TYPE, TREE_OBJ) {
    			var check_move = false;
    			return check_move;
    			
    		},
    		onselect: function(NODE,TREE_OBJ) {
    			// TODO Add support to find a form and, if exists, drop the hierarchy item id into a hidden value.
    			var hierarchyItemId = $(NODE).attr("id") === "" ?
       			$(NODE).find("a:first").attr("id") :
       			$(NODE).attr("id") || 0;
    			
    			var level = getCurrentLevel($(NODE).find("a:first").attr("companyId"),
        				$(NODE).find("a:first").attr("level"));
       			
    			focusedHierarchyItem = {
    				"id": $(NODE).find("a:first").attr("id"),
    				"level": level,
    				"company": getCompany($(NODE).find("a:first").attr("companyId")),
    				"name": $(NODE).find("a:first").attr("name")

        		};
    			
    			IdentityProxy.changeHierarchyItem(hierarchyItemId, {
    			callback: refreshStatusDetail,
    			timeout: 5000,
    			errorHandler: function (message, exception) {
    				alert("Unable to change hierarchy location.\n\nReason: " + 
    					message); 
    					
    			}
    			
    		});
    		}
  		}
  		
	});
}

function refreshStatusDetail() {
	$("#hierarchyItemNameHandle").text(focusedHierarchyItem.company.name + ": " + focusedHierarchyItem.name);
	$("#hierarchyTreeDialog").dialog("close");
	
}

